package com.lzx.adx.report.util.biz.product;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class XhsChannelHelper {


    /**
     * 小红书上报封装
     * @param reportDTO
     * @param accountDTO
     * @return
     */
    public static String covertXhsReport(ReportDTO reportDTO, AccountDTO accountDTO) {
        long time = System.currentTimeMillis();
        Map<String,String> map=new LinkedHashMap<>();

        map.put("platform",reportDTO.getOs());
        map.put("ts_ms",String.valueOf(time));
        map.put("click_id",reportDTO.getBizRequestId());
        map.put("ip", reportDTO.getIp());



        if(StringUtils.isNotBlank(reportDTO.getOaidSum()) && !reportDTO.getOaidSum().contains("__")) {
            map.put("oaid_sum", reportDTO.getOaidSum());
        }
        if (StringUtils.isNotBlank(reportDTO.getOaid()) && !reportDTO.getOaid().contains("__")) {
            map.put("oaid", reportDTO.getOaid());
            map.put("oaid_sum", SecureUtil.md5(reportDTO.getOaid()));
        }

        if(StringUtils.isNotBlank(reportDTO.getHash_android_id()) && !reportDTO.getHash_android_id().contains("__")) {
            map.put("android_id_sum", reportDTO.getHash_android_id());
        }

        if(StringUtils.isNotBlank(reportDTO.getImeiSum()) && !reportDTO.getImeiSum().contains("__")) {
            map.put("imei_sum", reportDTO.getImeiSum());
        }

        if(StringUtils.isNotBlank(reportDTO.getIdfaSum()) && !reportDTO.getIdfaSum().contains("__")){
            map.put("idfa_sum", reportDTO.getIdfaSum());
        }

        if(StringUtils.isNotBlank(reportDTO.getIdfa()) && !reportDTO.getIdfa().contains("__")){
            map.put("idfa", reportDTO.getIdfa());
            map.put("idfa_sum", SecureUtil.md5(reportDTO.getIdfa()));
        }

        if(StringUtils.isNotBlank(reportDTO.getUser_agent())) {
            map.put("ua", URLEncoderDecoderTool.encodeURL(reportDTO.getUser_agent()));
        }

        String allCabackUrl = String.format(accountDTO.getDspCallbackUrl(), reportDTO.getBizRequestId());
        log.info("完整的回调地址{}",allCabackUrl);
        map.put("callback_url",allCabackUrl);

        String params = URLUtil.buildQuery(map, StandardCharsets.UTF_8);
        return  accountDTO.getDspReportUrl()+"?"+params;
    }
}
